package orange.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.orange.Factory;

public class DB {
	static int conCount = 0;

	public static void main(String[] args) throws SQLException {
		Connection con = DB.getInstance().getConnection();
		Statement s = con.createStatement();
		ResultSet rs = s.executeQuery("select * from orange_z_jinliang");
//		for(String sql:Factory.views_sql){
//			try {
//				s.execute(sql);
//			} catch (Exception e) {
//				// TODO: handle exception
//				System.out.println(sql);
//				e.printStackTrace();
//			}
//			
//		}
		if (rs != null) {
			rs.next();
			System.out.println("result find");
		}
		DB.getInstance().release(con);
	}

	private static int flag = 0;

	static DB instance;

	public static DB getInstance() {
		if (instance == null)
			instance = new DB();
		return instance;
	}

	private DB() {
		if (flag == 0) {
			// init();
		}
	}

	private Connection getConnectionFromDatabase() {
		Connection trueConn = null;
		try {

			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://122.205.95.84:3306/orangedb?user=orange&password=orange&useUnicode=true&characterEncoding=utf-8";

			trueConn = DriverManager.getConnection(url);
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("sql exception" + ex.toString());
		}
		conCount++;
		return trueConn;
	}

	public Connection getConnection() {
		return getConnectionFromDatabase();
	}

	public boolean release(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			conn = null;
		}
		return true;
	}
	
	/**
	 * 数据库操作（增、删、改）
	 * 
	 * @param sql
	 *            要执行的SQL语句
	 * @return returnCode 1500 服务器错误 1000 执行成功 1062 已经存在
	 */
	public boolean doDbOperate(String sql) {
		System.out.println(sql);
		Connection conn = DB.getInstance().getConnection();
		boolean returnCode;
		try {
			Statement stmt = conn.createStatement();
			stmt.execute(sql);
			returnCode = true;
		} catch (SQLException e) {
			// TODO: handle exception
			System.out.println(e.toString());
			returnCode = false;
		}
		DB.getInstance().release(conn);
		return returnCode;
	}
}